<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true" class="demo-form-inline">

          <el-form-item>
            <el-button type="primary" @click="showAddDialog">添加</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="oname" placeholder="请输入要搜索的姓名" @input="selectByPage(1)" />
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="ophone" placeholder="请输入要搜索的手机号" @input="selectByPage(1)" />
          </el-form-item>
          <!-- 添加导入按钮 -->
          <el-form-item>
            <el-upload
                ref="upload"
                action='http://localhost:8080/admin/owner/up'
                accept=".csv"
                :headers="headers"
                :on-change="handleImport"
                :before-upload="beforeImport"
                :show-file-list="false">
              <el-button type="primary">
                <i class="el-icon-upload"></i> 导入业主信息
              </el-button>
            </el-upload>
          </el-form-item>
          <!-- 添加导出按钮 -->
          <el-form-item>
            <el-button type="success" @click="handleExport">
              <i class="el-icon-download"></i> 导出业主信息
            </el-button>
          </el-form-item>
        </el-form>
        <el-table :data="pageInfo.list" style="width: 100%">
          <el-table-column prop="oid" label="ID" width="65px" />
          <el-table-column prop="oavater" label="业主头像" width="90px">
            <template #default="scope">
              <el-avatar shape="square" :size="50"
                         :src="'http://localhost:8080/upload/' + scope.row.oavater" />
            </template>
          </el-table-column>
          <el-table-column prop="oname" label="业主姓名" width="90px" />
          <el-table-column prop="ogender" label="业主性别" width="100px">
            <template #default="scope">
              <span>{{ scope.row.ogender === 1 ? '男' : '女' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ophone" label="业主电话" width="180px" />
          <el-table-column prop="oadd" label="业主住址" width="115px" />
          <el-table-column prop="admin.username" label="业主账户" width="80px" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="primary" @click="selectByoid(scope.row.oid)">修改</el-button>
              <el-button size="small" type="primary" @click="selectByoid1(scope.row.oid)">添加账密</el-button>
              <el-button size="small" type="primary" @click="selectByoid2(scope.row.oid)">修改账密</el-button>
              <el-popconfirm title="确认删除?" confirm-button-text="确认" cancel-button-text="取消"
                             @confirm="deleteByRid(scope.row.oid)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="row-bg" justify="center" style="margin-top:20px ;">
          <el-pagination background layout="prev, pager, next" :total="pageInfo.total"
                         :page-size="pageInfo.pageSize" @change="selectByPage" />
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <!--添加业主对话框开始 -->
  <el-dialog v-model="addDialogShow" title="添加业主" width="500">
    <el-form>
      <el-form-item label="业主姓名" label-width="20%">
        <el-input v-model="ownerAdd.oname" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主性别" label-width="20%">
        <el-radio-group v-model="ownerAdd.ogender">
          <el-radio value="1" size="large">男</el-radio>
          <el-radio value="2" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="业主电话" label-width="20%">
        <el-input v-model="ownerAdd.ophone" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主住址" label-width="20%">
        <el-input v-model="ownerAdd.oadd" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="头像" label-width="20%">
        <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload" name="pic"
                   :headers="headers" :show-file-list="false" :before-upload="beforeAvatarUpload"
                   :on-success="handleAvatarSuccess">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">取消</el-button>
        <el-button type="primary" @click="insert">确定</el-button>
      </div>
    </template>

  </el-dialog>
  <!--添加业主对话框结束 -->
  <!--修改业主对话框开始 -->
  <el-dialog v-model="updateDialogShow" title="修改业主" width="500">
    <el-form>
      <el-form-item label="业主姓名" label-width="20%">
        <el-input v-model="ownerUpdate.oname" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主性别" label-width="20%">
        <el-radio-group v-model="ownerUpdate.ogender">
          <el-radio value="1" size="large">男</el-radio>
          <el-radio value="2" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="业主电话" label-width="20%">
        <el-input v-model="ownerUpdate.ophone" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主住址" label-width="20%">
        <el-input v-model="ownerUpdate.oadd" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="头像" label-width="20%">
        <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload" name="pic"
                   :headers="headers" :show-file-list="false" :before-upload="beforeAvatarUpload"
                   :on-success="handleAvatarUpdateSuccess">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">取消</el-button>
        <el-button type="primary" @click="update">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改业主对话框结束 -->
  <!--添加业主账密对话框开始 -->
  <el-dialog v-model="AddUpDialogShow" title="添加业主账密" width="500">
    <el-form>
      <el-form-item label="业主oid" label-width="20%" v-show="false">
        <el-input v-model="upAdd.oid" autocomplete="off" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="业主权限" label-width="20%" v-show="false">
        <el-input v-model="upAdd.root" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主用户名" label-width="20%">
        <el-input v-model="upAdd.username" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主密码" label-width="20%">
        <el-input v-model="upAdd.password" autocomplete="off" style="width: 300px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="AddUpDialogShow = false">取消</el-button>
        <el-button type="primary" @click="insertUp">确定</el-button>
      </div>
    </template>

  </el-dialog>
  <!--添加业主账密对话框结束 -->
  <!--修改业主账密对话框开始 -->
  <el-dialog v-model="updateUpDialogShow" title="修改业主账密" width="500">
    <el-form>
      <el-form-item label="业主oid" label-width="20%" v-show="false">
        <el-input v-model="upUpdate.oid" autocomplete="off" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="业主权限" label-width="20%" v-show="false">
        <el-input v-model="upUpdate.root" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主用户名" label-width="20%">
        <el-input v-model="upUpdate.username" autocomplete="off" style="width: 300px" />
      </el-form-item>
      <el-form-item label="业主密码" label-width="20%">
        <el-input v-model="upUpdate.password" autocomplete="off" style="width: 300px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateUpDialogShow = false">取消</el-button>
        <el-button type="primary" @click="updateUp">确定</el-button>
      </div>
    </template>

  </el-dialog>
  <!--修改业主账密对话框结束 -->
</template>

<script setup>
import departmentApi from '@/api/departmentApi';
import ownerApi from '@/api/ownerApi';
import loginApi from '@/api/loginApi';
import { computed, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { ElLoading } from 'element-plus';
import axios from "axios";
import LoginApi from "@/api/loginApi.js";
import {useTokenStore} from "@/stores/token.js";

const tokenStore = useTokenStore()
//用于搜索姓名关键字
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
});
const oname = ref('')
const ophone = ref('')
//用于分页
const pageInfo = ref({
  total: 0,
  pageSize: 0,
});
const upAdd = ref({
  oid: '0',
  username: '',
  password: '',
  root: '2',
});
const upUpdate = ref({
  oid: 0,
  username: '',
  password: '',
  root: 2
});
//被添加业主信息
const ownerAdd = ref({
  oname: '',
  ogender: '1',
  ophone: '',
  oadd: '',
  oavater: '',


});
const ownerUpdate = ref({
  oid: 0,
  oname: '',
  ogender: '',
  ophone: '',
  oavater: '',
  oadd: '',
});

//上传图片的地址
const imageUrl = ref("");

//用于添加业主对话框
const addDialogShow = ref(false);
const updateDialogShow = ref(false);
const AddUpDialogShow = ref(false);
const updateUpDialogShow = ref(false);
const root = LoginApi.select().then(resp=>{return resp.data})
console.log(root )


//导出功能
function handleExport() {
  axios.get('http://localhost:8080/admin/owner/export', {
    headers: { // 头部参数
      token: tokenStore.tokenStr
    },
    responseType: 'text' // 确保响应类型为文本
  })
      .then((response) => {
        const csvContent = response.data;
        const data = parseCSV(csvContent); // 解析 CSV 数据
        if (Array.isArray(data)) {
          const csvContent = convertToCSV(data);
          downloadCSV(csvContent, '业主信息.csv');
        } else {
          console.error('Data is not an array:', data);
          alert('导出失败，请检查数据格式');
        }
      })
      .catch((error) => {
        console.error('Error during data fetching:', error);
        alert('导出失败，请检查网络连接或联系管理员');
      });
}

// 解析 CSV 内容为数组
function parseCSV(csvContent) {
  const lines = csvContent.split('\n');
  const headers = lines[0].split(',');
  return lines.slice(1).map(line => {
    const values = line.split(',');
    return headers.reduce((obj, header, index) => {
      obj[header] = values[index];
      return obj;
    }, {});
  });
}

// 将数据转换为 CSV 格式
function convertToCSV(data) {
  if (!Array.isArray(data) || data.length === 0) {
    console.error('Invalid data for CSV conversion:', data);
    return '';
  }

  const headers = 'ID,业主姓名,业主性别,业主电话,业主头像,业主住址\n';
  const rows = data.map(item =>
      `${item.ID || ''},${item.业主姓名 || ''},${item.业主性别 || ''},${item.业主电话 || ''},${item.业主头像 || ''},${item.业主住址 || ''}`
  ).join('\n');

  return headers + rows;
}

// 触发 CSV 文件下载
function downloadCSV(csvContent, filename) {
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.href = url;
  link.download = filename;
  link.click();
  URL.revokeObjectURL(url);
}




function updateUp() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  loginApi.updateByOid(upUpdate.value)
      .then(resp => {
        loading.close()
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          updateUpDialogShow.value = false;

          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 2000
          });
        }
      });
}
function insertUp() {
  console.log(upAdd.value);
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  loginApi.insert(upAdd.value)
      .then(resp => {
        loading.close()
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          AddUpDialogShow.value = false;

          upAdd.value = {
            username: '',
            password: '',
            root: 2,
            oid: 0
          }
          //imgUrl清空
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 2000
          });
        }
      });
}

//上传图片前的回调
function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2m')
    return false
  }
  return true
}
//上传图片成功的回调
function handleAvatarSuccess(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg)
    imageUrl.value = "http://localhost:8080/upload/" + resp.data;
    ownerAdd.value.oavater = resp.data;
  }
}

function selectByPage(pageNum) {
  ownerApi.selectByPage(pageNum, oname.value, ophone.value)
      .then(resp => {
        pageInfo.value = resp.data;
      });
}
function handleAvatarUpdateSuccess(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg)
    imageUrl.value = "http://localhost:8080/upload/" + resp.data;
    ownerUpdate.value.oavater = resp.data;
  }
}


function showAddDialog() {
  addDialogShow.value = true;
}
//添加
function insert() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  ownerApi.insert(ownerAdd.value)
      .then(resp => {
        loading.close()
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          addDialogShow.value = false;

          ownerAdd.value = {
            oname: '',
            ogender: '',
            ophone: '',
            oadd: '',
            oavater: '',
            oid: 0
          }
          //imgUrl清空
          imageUrl.value = "";
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 2000
          });
        }
      });
}
//删除
function deleteByRid(oid) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  ownerApi.delete(oid)
      .then(resp => {
        loading.close()
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200

          });
          loginApi.deleteByOid(oid);
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 2000
          });
        }
      });
}
function update() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  ownerApi.update(ownerUpdate.value)
      .then(resp => {
        loading.close()
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          updateDialogShow.value = false;

          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 2000
          });
        }
      });
}
function selectByoid(oid) {
  ownerApi.selectByOid(oid)
      .then(resp => {
        ownerUpdate.value = resp.data;
        updateDialogShow.value = true;
      });
}
function selectByoid1(oid) {
  ownerApi.selectByOid(oid)
      .then(resp => {
        upAdd.value = resp.data;
        upAdd.value.root = 2;
        AddUpDialogShow.value = true;
      });
}
function selectByoid2(oid) {
  ownerApi.selectByOid(oid)
      .then(resp => {
        upUpdate.value = resp.data;
        upUpdate.value.root = 2;
        updateUpDialogShow.value = true;
      });
}
//默认查询首页
selectByPage(1);
</script>

<style scoped>
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>